#include "equipnode.h"

#include <osgDB/ReadFile>
#include <osgGA/StateSetManipulator>
#include <osg/Material>
#include <boost/filesystem.hpp>

EquipNode::EquipNode(const std::string& fName)
{
    bLoaded = false;
    equip = osgDB::readNodeFile(fName);
    setColor(osg::Vec4(0.9, 0.9, 0.9, 0.2));

    position = new osg::MatrixTransform();
    rotate = new osg::MatrixTransform();

    if (equip.valid())
    {
        boost::filesystem::path ph = fName;
        name_ = ph.stem().string();

        veh = new osg::Group();
        rotate->addChild(equip);
        veh->addChild(rotate);

        position->addChild(rotate);
        veh->addChild(position);

        position->getOrCreateStateSet()->setMode(GL_RESCALE_NORMAL, osg::StateAttribute::ON);
        bLoaded = true;
    }
}

void EquipNode::setPosition(const osg::Vec3 pos)
{
    pos_ = pos;

    csn = new osg::CoordinateSystemNode();
    csn->setEllipsoidModel(new osg::EllipsoidModel);

    osg::Matrixd mtTemp;
    csn->getEllipsoidModel()->computeLocalToWorldTransformFromLatLongHeight(
                osg::DegreesToRadians(pos.x()),
                osg::DegreesToRadians(pos.y()),
                pos.z(),
                mtTemp);
    position->setMatrix(mtTemp);
}

void EquipNode::setRotoate(const osg::Vec3 rot)
{
    rot_ = rot;
    osg::Quat _rotation;
    _rotation.makeRotate(rot.x(), osg::X_AXIS, rot.y(), osg::Y_AXIS, rot.z(), osg::Z_AXIS);
    osg::Matrix mat;
    mat.preMultRotate(_rotation);
    rotate->setMatrix(mat);
}


void EquipNode::setColor(const osg::Vec4 rgba)
{
    if (!bLoaded) return;

    clr_ = osg::Vec3(rgba.x(), rgba.y(), rgba.z());
    capacity_ = rgba.w();
    osg::StateSet* state = equip->getOrCreateStateSet();
    state->setMode(GL_BLEND, osg::StateAttribute::ON);
    osg::ref_ptr<osg::Material> mat = new osg::Material;
    mat->setDiffuse(osg::Material::FRONT_AND_BACK, rgba);
    mat->setAmbient(osg::Material::FRONT_AND_BACK, rgba);
    mat->setTransparency(osg::Material::FRONT_AND_BACK, capacity_);
    state->setAttributeAndModes(mat, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON);
    state->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
}

